package main

import (
	"errors"
	"fmt"
	"log"
	"math/rand"
	"time"

	sentinel "github.com/alibaba/sentinel-golang/api"
	"github.com/alibaba/sentinel-golang/core/circuitbreaker"
	"github.com/alibaba/sentinel-golang/core/config"
	"github.com/alibaba/sentinel-golang/logging"
	"github.com/alibaba/sentinel-golang/util"
)

type stateChangeTestListener struct{}

var totalEnter = 0
var errCount = 0

func (s *stateChangeTestListener) OnTransformToClosed(prev circuitbreaker.State, rule circuitbreaker.Rule) {
	fmt.Printf("熔断器关闭了 rule.steategy: %+v, From %s to Closed, time: %d\n", rule.Strategy, prev.String(), util.CurrentTimeMillis())
}

func (s *stateChangeTestListener) OnTransformToOpen(prev circuitbreaker.State, rule circuitbreaker.Rule, snapshot interface{}) {
	fmt.Println("ratio", float64(errCount)/float64(totalEnter))
	fmt.Println("totalEnter", totalEnter)
	fmt.Println("errCount", errCount)
	totalEnter = 0
	errCount = 0
	fmt.Printf("熔断器打开了 rule.steategy: %+v, From %s to Open, snapshot: %.2f, time: %d\n", rule.Strategy, prev.String(), snapshot, util.CurrentTimeMillis())
}

func (s *stateChangeTestListener) OnTransformToHalfOpen(prev circuitbreaker.State, rule circuitbreaker.Rule) {
	fmt.Printf("熔断器半打开 rule.steategy: %+v, From %s to Half-Open, time: %d\n", rule.Strategy, prev.String(), util.CurrentTimeMillis())
}

func main() {
	conf := config.NewDefaultConfig()
	conf.Sentinel.Log.Logger = logging.NewConsoleLogger()
	err := sentinel.InitWithConfig(conf)
	if err != nil {
		log.Fatal(err)
	}

	ch := make(chan struct{})
	circuitbreaker.RegisterStateChangeListeners(&stateChangeTestListener{})

	_, err = circuitbreaker.LoadRules([]*circuitbreaker.Rule{
		{
			Resource:         "abc",
			Strategy:         circuitbreaker.ErrorRatio,
			RetryTimeoutMs:   3000, // 3秒之后尝试恢复
			MinRequestAmount: 10,   // 静默数, 10个以内全部通过
			StatIntervalMs:   5000, // 5秒钟统计一次
			Threshold:        0.4,  // 错误率不超过40%
		},
	})
	if err != nil {
		log.Fatal(err)
	}

	logging.Info("[CircuitBreaker ErrorCount] Sentinel Go circuit breaking demo is running. You may see the pass/block metric in the metric log.")
	go func() {
		for {
			e, b := sentinel.Entry("abc")
			totalEnter++
			if b != nil {
				// g1 blocked
				fmt.Println("g1 blocked")
				time.Sleep(time.Duration(rand.Uint64()%20) * time.Millisecond)
			} else {
				if rand.Uint64()%20 > 10 {
					errCount++
					sentinel.TraceError(e, errors.New("biz error"))
				}
				// g1 passed
				time.Sleep(time.Duration(rand.Uint64()%80+10) * time.Millisecond)
				e.Exit()
			}
		}
	}()
	//go func() {
	//	for {
	//		e, b := sentinel.Entry("abc")
	//		totalEnter++
	//		if b != nil {
	//			// g2 blocked
	//			time.Sleep(time.Duration(rand.Uint64()%20) * time.Millisecond)
	//		} else {
	//			// g2 passed
	//			time.Sleep(time.Duration(rand.Uint64()%80) * time.Millisecond)
	//			e.Exit()
	//		}
	//	}
	//}()

	go func() {
		for range time.Tick(time.Second) {
			fmt.Println("totalEnter", totalEnter)
			fmt.Println("errCount", errCount)
			fmt.Println("ratio", float64(errCount)/float64(totalEnter))
			fmt.Println("===================")
		}
	}()

	<-ch
}
